<?php
/**
 * 采购单控制器
 */

namespace app\api\controller;

use app\api\exception\ApiServiceException;
use app\api\service\SendService;
use app\common\model\Brand;
use app\common\model\Offer;
use app\common\model\OfferDetail;
use app\common\model\Send;
use app\common\model\Spec;
use app\common\model\Type;
use app\common\validate\SendValidate;
use hg\apidoc\annotation as Apidoc;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Request;
use think\response\Json;

/**
 * @Apidoc\Title("送货单")
 * @Apidoc\Group("index")
 */
class SendController extends ApiBaseController {
	protected array $loginExcept = [
		'api/send/info',
	];

	/**
	 * @Apidoc\Title("列表")
	 * @Apidoc\Desc("列表")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/api/send/index")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function index(SendService $service): Json {
		try {
			$this->param['user_id'] = $this->uid;
			$data = $service->getList($this->param, $this->page, $this->limit);
			$result = [
				'send' => $data,
			];

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 添加
	 * @param SendValidate $validate
	 * @param SendService $service
	 * @return Json
	 */
	public function add(SendValidate $validate, SendService $service): Json {
		$check = $validate->scene('api_add')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		$result = $service->createData($this->param);

		return $result ? api_success() : api_error();
	}

	/**
	 * @Apidoc\Title("详情")
	 * @Apidoc\Desc("详情")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/api/send/info")
	 * @Apidoc\Query("id",          type="int",require=true, desc="id")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function info(SendValidate $validate, SendService $service): Json {

		try {

			$result = $service->getDataInfo($this->id);
			return api_success([
				'send' => $result,
			]);

		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	public function edit(SendService $service, SendValidate $validate): Json {
		$this->param['detail'] = json_decode($this->param['detail'], true);
		$detail = $this->param['detail'];
		foreach ($detail as $key => $value) {
			$detail[$key]['money'] = round($value['num'] * $value['price'], 2);
		}
		$this->param['detail'] = $detail;
		$data = Send::findOrEmpty($this->id);
		$offer = OfferDetail::where('send_id', $data['id'])->findOrEmpty();
		if (!$offer->isEmpty()) {
			$offer_detail = $offer['detail'];
			foreach ($offer['detail'] as $key => $Value) {

				$offer_detail[$key]['type_id'] = $this->param['detail'][$key]['type_id'];
				$offer_detail[$key]['spec_id'] = $this->param['detail'][$key]['spec_id'];
				$offer_detail[$key]['brand_id'] = $this->param['detail'][$key]['brand_id'];
				$offer_detail[$key]['num'] = $this->param['detail'][$key]['num'];
				$offer_detail[$key]['money'] = round($offer_detail[$key]['num'] * $offer_detail[$key]['price'], 2);
			}
			$offer_money = array_sum(array_column($offer_detail, 'money'));
			$offer->save(['detail' => $offer_detail, 'money' => $offer_money]);

			$offer_detail_list = OfferDetail::where('offer_id', $offer['offer_id'])->select()->toArray();
			$filter_detail = array_column($offer_detail_list, 'detail');
			$twoDimArray = [];

			// 遍历三维数组，将其转换为二维数组
			foreach ($filter_detail as $subArray) {
				foreach ($subArray as $item) {
					$twoDimArray[] = $item;
				}
			}

			$filter_detail = $this->array_do($twoDimArray);

			$offer_data = [
				'money' => array_sum(array_column($offer_detail_list, 'money')),
				'detail' => $filter_detail,
			];
			$offer = Offer::where('id', $offer['offer_id'])->update($offer_data);
		}
		$this->param['money'] = array_sum(array_column($this->param['detail'], 'money'));
		try {
			$service->updateData($this->id, $this->param);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 删除
	 * @param SendService $service
	 * @param SendValidate $validate
	 * @return Json
	 */
	public function del(SendService $service, SendValidate $validate): Json {
		$check = $validate->scene('api_del')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->deleteData($this->id);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}
	public function export(Request $request, Send $model): void {
		$param = $request->param();
		$data = $model->with(['school', 'user'])->where('id', $param['id'])->find();

		$head = ['商品名称', '单位', '待采购量', '采购价格', '备注', '商品状态', '客户下单明细', '商品条码', '商品编码'];
		$status = [
			'0' => '待采购',
			'1' => '已采购',
			'2' => '待送货',
			'3' => '已送货',
		];
		$body = [];
		foreach ($data['detail'] as $item) {
			$type = Type::where('id', $item['type_id'])->find();
			$spec = Spec::where('id', $item['spec_id'])->find();
			$brand = Brand::where('id', $item['brand_id'])->find();
			$record = [];
			$record['name'] = $type['name'];
			$record['brand'] = $brand['name'];
			$record['num'] = $item['num'];
			$record['price'] = $item['price'];
			$record['beizhu'] = ' ';
			$record['status'] = $status[$item['status']];
			$record['mx'] = '';
			$record['tm'] = '';
			$record['bm'] = '';

			$body[] = $record;
		}
		try {
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->setActiveSheetIndex(0);

			$sheet->mergeCells("A1:H1"); //合并单元格
			$sheet->mergeCells("B2:C2"); //合并单元格
			$sheet->mergeCells("E2:F2"); //合并单元格
			$sheet->mergeCells("B3:C3"); //合并单元格
			$sheet->mergeCells("E3:F3"); //合并单元格
			$sheet->setCellValue("A1", "送货单(" . $data->user->nickname . ")")->getStyle('A1')->getFont()->setBold(true);
			$sheet->setCellValue("A2", "单据编号")->getStyle('A2')->getFont()->setBold(true);
			$sheet->setCellValue("B2", $data->code . ' ')->getStyle('B2')->getFont()->setBold(true);
			$sheet->setCellValue("D2", "发货日期")->getStyle('D2')->getFont()->setBold(true);
			$sheet->setCellValue("E2", $data->send_time)->getStyle('E2')->getFont()->setBold(true);
			$sheet->setCellValue("G2", "单据金额")->getStyle('G2')->getFont()->setBold(true);
			$sheet->setCellValue("H2", $data->money)->getStyle('H2')->getFont()->setBold(true);
			$sheet->setCellValue("A3", "创建时间")->getStyle('A3')->getFont()->setBold(true);
			$sheet->setCellValue("B3", $data->create_time)->getStyle('B3')->getFont()->setBold(true);
			$sheet->setCellValue("D3", "单据备注")->getStyle('D3')->getFont()->setBold(true);
			$sheet->setCellValue("G3", "单据状态")->getStyle('G3')->getFont()->setBold(true);
			$sheet->setCellValue("H3", $data->status_text)->getStyle('H3')->getFont()->setBold(true);
			$char_index = range('A', 'Z');
			$name = '采购单数据-' . date('YmdHis');
			// 处理超过26列
			$a = 'A';
			foreach ($char_index as $item) {
				$char_index[] = $a . $item;
			}

			// Excel 表格头
			foreach ($head as $key => $val) {
				$sheet->setCellValue($char_index[$key] . '5', $val);
			}

			// Excel body 部分
			foreach ($body as $key => $val) {
				$row = $key + 6;
				$col = 0;
				foreach ($val as $v) {
					$sheet->setCellValue($char_index[$col] . $row, $v);
					$col++;
				}
			}

			$spreadsheet->getActiveSheet()->setTitle('采购单');

			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
			header('Cache-Control: max-age=0');

			$objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
			$objWriter->save('php://output');
			exit();
		} catch (Exception $e) {
			exit($e->getMessage() . '(' . $e->getFile() . '-' . $e->getLine() . ')');
		}
	}

}
